<template>
  <div class="site-management">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">站点管理</h1>
          <p class="page-desc">管理您的所有站点，包括域名配置、主题设置等</p>
        </div>
        <div class="header-right">
          <div class="stats-section">
            <div class="stat-item">
              <span class="stat-number">{{ siteTree.length }}</span>
              <span class="stat-label">总站点</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ activeSiteCount }}</span>
              <span class="stat-label">活跃站点</span>
            </div>
          </div>
          <el-button type="primary" size="large" @click="handleAdd" class="add-btn">
            <el-icon><Plus /></el-icon>
            新建站点
          </el-button>
        </div>
      </div>
    </div>

    <div class="site-grid" v-loading="loading">
      <div
        v-for="site in siteTree"
        :key="site.id"
        class="site-card"
        :class="{ 'site-card--disabled': site.status === 0 }"
      >
        <div class="site-card__header">
          <div class="site-info">
            <div class="site-logo-wrapper">
              <el-image
                v-if="site.logo"
                :src="site.logo"
                class="site-logo"
                fit="cover"
              />
              <div v-else class="site-logo site-logo--default">
                <el-icon><House /></el-icon>
              </div>
            </div>
            <div class="site-details">
              <h3 class="site-name">{{ site.name }}</h3>
              <p class="site-domain">
                <el-icon><Link /></el-icon>
                {{ site.domain || '未设置域名' }}
              </p>
            </div>
          </div>
          <div class="site-actions">
            <el-switch
              v-model="site.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(site)"
            />
            <el-dropdown @command="(command) => handleMoreAction(command, site)" trigger="click">
              <el-button text circle :icon="MoreFilled" class="more-btn" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit"><el-icon><Edit /></el-icon>编辑站点</el-dropdown-item>
                  <el-dropdown-item command="addChild"><el-icon><Plus /></el-icon>添加子站点</el-dropdown-item>
                  <el-dropdown-item command="preview" divided><el-icon><View /></el-icon>预览</el-dropdown-item>
                  <el-dropdown-item command="copy"><el-icon><CopyDocument /></el-icon>复制站点</el-dropdown-item>
                  <el-dropdown-item command="delete" class="danger-item"><el-icon><Delete /></el-icon>删除站点</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="site-card__body">
          <div class="meta-grid">
            <div class="meta-item meta-item--full" v-if="site.description">
              <span class="meta-label"><el-icon><Document /></el-icon>描述</span>
              <p class="meta-value">{{ site.description }}</p>
            </div>
            <div class="meta-item">
              <span class="meta-label"><el-icon><Brush /></el-icon>主题</span>
              <span class="meta-value">{{ site.theme || '默认' }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label"><el-icon><Sort /></el-icon>排序</span>
              <span class="meta-value">{{ site.orderNum }}</span>
            </div>
            <div class="meta-item meta-item--full">
              <span class="meta-label"><el-icon><Calendar /></el-icon>创建时间</span>
              <span class="meta-value">{{ formatDate(site.createdAt) }}</span>
            </div>
          </div>
        </div>
        
        </div>

      <div v-if="!loading && siteTree.length === 0" class="empty-state">
        <el-empty description="暂无站点数据">
          <el-button type="primary" @click="handleAdd">创建第一个站点</el-button>
        </el-empty>
      </div>
    </div>
    
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入站点名称" />
        </el-form-item>
        
        <el-form-item label="域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入域名" />
        </el-form-item>
        
        <el-form-item label="站点Logo" prop="logo">
          <div class="upload-section">
            <!-- 简化的上传组件 -->
            <el-upload
              class="logo-uploader"
              action="/cms/admin/attachment/upload"
              :headers="{ 'Authorization': 'Bearer ' + (getToken() || '') }"
              :data="{ siteId: 1, userId: 1 }"
              :show-file-list="false"
              :on-success="handleLogoUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeLogoUpload"
              accept="image/*"
              drag
            >
              <div class="upload-content">
                <img v-if="form.logo" :src="form.logo" class="logo-preview" />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击或拖拽上传Logo</div>
                </div>
              </div>
            </el-upload>
            <div class="upload-tips">
              <p>建议尺寸：200x60px，支持 JPG、PNG 格式，文件大小不超过 2MB</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="站点图标" prop="favicon">
          <div class="upload-section">
            <!-- 简化的上传组件 -->
            <el-upload
              class="favicon-uploader"
              action="/cms/admin/attachment/upload"
              :headers="{ 'Authorization': 'Bearer ' + (getToken() || '') }"
              :data="{ siteId: 1, userId: 1 }"
              :show-file-list="false"
              :on-success="handleFaviconUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeFaviconUpload"
              accept="image/*"
              drag
            >
              <div class="upload-content">
                <img v-if="form.favicon" :src="form.favicon" class="favicon-preview" />
                <div v-else class="upload-placeholder favicon-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击或拖拽上传图标</div>
                </div>
              </div>
            </el-upload>
            <div class="upload-tips">
              <p>建议尺寸：32x32px 或 64x64px，支持 ICO、PNG 格式，文件大小不超过 1MB</p>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="SEO关键词" prop="keywords">
          <el-input
            v-model="form.keywords"
            type="textarea"
            :rows="2"
            placeholder="请输入SEO关键词，多个关键词用逗号分隔"
          />
        </el-form-item>
        
        <el-form-item label="SEO描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入SEO描述"
          />
        </el-form-item>
        
        <el-form-item label="主题" prop="theme">
          <el-select v-model="form.theme" placeholder="请选择主题">
            <el-option label="默认主题" value="default" />
            <el-option label="简约主题" value="simple" />
            <el-option label="商务主题" value="business" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上级站点" prop="parentId" v-if="!isEdit">
          <el-tree-select
            v-model="form.parentId"
            :data="siteTreeOptions"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级站点"
            check-strictly
            clearable
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus, House, Edit, Delete, Check, Link, Brush, Sort, Calendar,
  View, CopyDocument, MoreFilled, Document
} from '@element-plus/icons-vue'
import { siteApi } from '@/api/site'
import type { Site } from '@/types/api'

// 简单的token获取函数
const getToken = () => {
  return localStorage.getItem('token') || ''
}

const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()



// 站点树数据
const siteTree = ref<Site[]>([])

// 上传配置
const uploadUrl = ref('/cms/admin/attachment/upload')
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${getToken()}`
}))
const uploadData = computed(() => ({
  siteId: 1, // 默认站点ID
  userId: 1  // 默认用户ID
}))

// 表单数据
const form = ref<Partial<Site>>({
  name: '',
  domain: '',
  logo: '',
  favicon: '',
  keywords: '',
  description: '',
  theme: 'default',
  parentId: 0,
  orderNum: 999999,
  status: 1,
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入站点名称', trigger: 'blur' },
    { min: 1, max: 100, message: '站点名称长度在 1 到 100 个字符', trigger: 'blur' },
  ],
  domain: [
    { max: 100, message: '域名长度不能超过 100 个字符', trigger: 'blur' },
  ],
  keywords: [
    { max: 500, message: 'SEO关键词长度不能超过 500 个字符', trigger: 'blur' },
  ],
  description: [
    { max: 1000, message: 'SEO描述长度不能超过 1000 个字符', trigger: 'blur' },
  ],
}

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑站点' : '新建站点')

// 活跃站点计数
const activeSiteCount = computed(() => {
  const countActive = (sites: Site[]): number => {
    return sites.reduce((count, site) => {
      return count + (site.status === 1 ? 1 : 0) + (site.children ? countActive(site.children) : 0)
    }, 0)
  }
  return countActive(siteTree.value)
})

// 站点树选项（用于选择上级站点）
const siteTreeOptions = computed(() => {
  const options = [{ id: 0, name: '顶级站点', children: [] }]
  options[0].children = siteTree.value
  return options
})

// 获取站点树
const getSiteTree = async () => {
  try {
    loading.value = true
    const response = await siteApi.getSiteTree()
    siteTree.value = response.data
  } catch (error) {
    console.error('获取站点树失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理添加子站点
const handleAddChild = (row: Site) => {
  isEdit.value = false
  form.value.parentId = row.id
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: Site) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: Site) => {
  ElMessageBox.confirm(`确定要删除站点"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await siteApi.deleteSite(row.id)
      ElMessage.success('删除成功')
      getSiteTree()
    } catch (error) {
      console.error('删除站点失败:', error)
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: Site) => {
  try {
    await siteApi.updateSiteStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 处理更多操作 (已更新，包含所有操作)
const handleMoreAction = (command: string, site: Site) => {
  switch (command) {
    case 'edit':
      handleEdit(site)
      break
    case 'addChild':
      handleAddChild(site)
      break
    case 'preview':
      handlePreview(site)
      break
    case 'copy':
      handleCopy(site)
      break
    case 'delete':
      handleDelete(site)
      break
  }
}

// 处理预览
const handlePreview = (site: Site) => {
  if (site.domain) {
    window.open(`http://${site.domain}`, '_blank')
  } else {
    ElMessage.warning('该站点未配置域名，无法预览')
  }
}

// 处理复制
const handleCopy = (site: Site) => {
  const copyData = {
    ...site,
    id: undefined,
    name: `${site.name}_副本`,
    domain: '',
    createdAt: undefined,
    updatedAt: undefined
  }

  form.value = copyData
  isEdit.value = false
  dialogVisible.value = true
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await siteApi.updateSite(form.value.id!, form.value)
      ElMessage.success('更新成功')
    } else {
      await siteApi.createSite(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    getSiteTree()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    domain: '',
    logo: '',
    favicon: '',
    keywords: '',
    description: '',
    theme: 'default',
    parentId: 0,
    orderNum: 999999,
    status: 1,
  }
  formRef.value?.resetFields()
}

// Logo上传前验证
const beforeLogoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// Logo上传成功处理
const handleLogoUploadSuccess = (response: any) => {
  if (response.code === 0) {
    form.value.logo = response.data.url
    ElMessage.success('Logo上传成功')
  } else {
    ElMessage.error(response.msg || 'Logo上传失败')
  }
}

// Favicon上传前验证
const beforeFaviconUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt1M = file.size / 1024 / 1024 < 1

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt1M) {
    ElMessage.error('图标大小不能超过 1MB!')
    return false
  }
  return true
}

// Favicon上传成功处理
const handleFaviconUploadSuccess = (response: any) => {
  if (response.code === 0) {
    form.value.favicon = response.data.url
    ElMessage.success('图标上传成功')
  } else {
    ElMessage.error(response.msg || '图标上传失败')
  }
}

// 上传错误处理
const handleUploadError = (error: any) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败: ' + (error.message || '网络错误'))
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

onMounted(() => {
  getSiteTree()
})
</script>

<style scoped lang="scss">
/* ==========================================================================
   Design System & CSS Variables (v3)
  ========================================================================== */
.site-management {
  --c-primary: #4f46e5;
  --c-primary-light: #eef2ff;
  --c-text-primary: #111827;
  --c-text-secondary: #374151;
  --c-text-tertiary: #6b7280;
  --c-danger: #ef4444;
  --c-border: #e5e7eb;
  --c-bg-page: #f9fafb;
  --c-bg-card: #ffffff;
  --c-bg-subtle: #f9fafb;
  --font-family: -apple-system, 'Helvetica Neue', Helvetica, Arial, sans-serif;
  --border-radius: 0.75rem;
  --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
  --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.06), 0 2px 4px -2px rgb(0 0 0 / 0.06);
  --transition: all 0.2s ease-in-out;
}

/* ==========================================================================
   Base & Page Layout
  ========================================================================== */
.site-management {
  padding: 24px 32px;
  background-color: var(--c-bg-page);
  min-height: 100vh;
  font-family: var(--font-family);
}

.page-header {
  margin-bottom: 24px;
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: cent
  }
  .title-section {
    .page-title {
      font-size: 1.875rem;
      font-weight: 600;
      color: var(--c-text-primary);
    }
    .page-desc {
      font-size: 1rem;
      color: var(--c-text-tertiary);
      margin-top: 4px;
    }
  }
  .header-right {
    display: flex;
    align-items: center;
    gap: 24px;
  }
  .stats-section {
    display: flex;
    gap: 24px;
    padding: 12px 16px;
    background-color: var(--c-bg-card);
    border: 1px solid var(--c-border);
    border-radius: var(--border-radius);
  }
  .stat-item {
    text-align: center;
    .stat-number {
      font-size: 1.5rem;
      font-weight: 600;
      color: var(--c-primary);
    }
    .stat-label {
      font-size: 0.75rem;
      color: var(--c-text-tertiary);
    }
  }
  .add-btn {
    border-radius: 8px;
    font-weight: 500;
  }
}

/* ==========================================================================
   Site Grid & Cards
  ========================================================================== */
.site-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 24px;
}

.site-card {
  display: flex;
  flex-direction: column;
  background: var(--c-bg-card);
  border-radius: var(--border-radius);
  border: 1px solid var(--c-border);
  box-shadow: var(--shadow-sm);
  transition: var(--transition);

  &:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-md);
  }
  &--disabled {
    filter: grayscale(80%);
    opacity: 0.6;
    &:hover { transform: none; box-shadow: var(--shadow-sm); }
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    flex-shrink: 0;

    .site-info {
      display: flex;
      align-items: center;
      gap: 12px;
      min-width: 0;
    }
    .site-logo {
      width: 40px; height: 40px;
      border-radius: 8px;
      &--default {
        background-color: var(--c-primary-light);
        color: var(--c-primary);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
      }
    }
    .site-details {
      min-width: 0;
      .site-name {
        font-size: 1.125rem;
        font-weight: 600;
        color: var(--c-text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .site-domain {
        font-size: 0.875rem;
        color: var(--c-text-tertiary);
        display: flex;
        align-items: center;
        gap: 6px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .site-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .more-btn {
      font-size: 1.25rem;
      color: var(--c-text-tertiary);
      transform: rotate(90deg);
      &:hover { background-color: var(--c-bg-subtle); }
    }
  }

  &__body {
    padding: 16px;
    padding-top: 0;
    flex-grow: 1;
    border-top: 1px solid var(--c-border);
  }
}

/* Meta Grid - The core fix for the "messy" layout */
.meta-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.meta-item {
  margin-top: 12px;
  background-color: var(--c-bg-subtle);
  border: 1px solid var(--c-border);
  border-radius: 8px;
  padding: 12px;
  font-size: 0.875rem;

  .meta-label {
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--c-text-secondary);
    font-size: 0.8125rem;
    margin-bottom: 8px;
    .el-icon { font-size: 1rem; }
  }

  .meta-value {
    color: var(--c-text-primary);
    font-weight: 500;
    word-wrap: break-word;
  }
  
  p.meta-value { 
      padding-left: 22px;
      margin: -4px 0 0;
  }

  &--full {
    grid-column: 1 / -1;
  }
}

// Style for the "Delete" item in the dropdown
:deep(.el-dropdown-menu__item.danger-item) {
    color: var(--c-danger);
    &:hover {
        background-color: #fee2e2;
        color: #b91c1c;
    }
}

/* 上传组件样式 */
.upload-section {
  .logo-uploader {
    :deep(.el-upload-dragger) {
      width: 200px;
      height: 80px;
      border: 2px dashed var(--el-border-color);
      border-radius: 8px;
      background: #fafafa;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
        background: #f0f9ff;
      }
    }
  }

  .favicon-uploader {
    :deep(.el-upload-dragger) {
      width: 80px;
      height: 80px;
      border: 2px dashed var(--el-border-color);
      border-radius: 8px;
      background: #fafafa;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
        background: #f0f9ff;
      }
    }
  }

  .upload-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .logo-preview, .favicon-preview {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }

  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--el-text-color-secondary);

    &.favicon-placeholder {
      padding: 10px;
    }

    .upload-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }
  }

  .upload-tips {
    margin-top: 8px;

    p {
      margin: 0;
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      line-height: 1.4;
    }
  }
}
</style>